package com.bjpowernode.security04mysql.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.imageio.ImageIO;
import java.io.IOException;

/**
 * 生成验证码图片
 */
@Controller
public class CaptchaController {

    @GetMapping("/code/image")
    public void code(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //hutool生成验证码图片
        /*
            codeCount 验证码的个数
            circleCount 干扰圆圈的个数

            circleCaptcha对象中包含了2项：验证码图片和验证码
         */
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(200, 100, 2, 400);

        //将验证码存入session中
        request.getSession().setAttribute("code", circleCaptcha.getCode());

        //将验证码图片以流的方式写出到浏览器中
        ImageIO.write(circleCaptcha.getImage(), "png", response.getOutputStream());
    }
}
